<?php
/**
 * 支付回调
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-09
 * Time: 15:33
 */

namespace App\Http\Controllers\Api\V1\Manager\Mall;


use App\Http\Controllers\Controller;
use App\Libs\Contracts\PayMent\AliPay\Web\pagepay\service\AlipayTradeService;
use App\Libs\Contracts\PayMent\Wxpay\WxPayApi;
use App\Models\Activity;
use App\Models\ActivityOrder;
use App\Models\ActivityOrderDetail;
use App\Models\ContractorCourse;
use App\Models\Course;
use App\Models\CourseOrder;
use App\Models\CourseOrderDetail;
use App\Models\Order;
use App\Models\PaymentCallback;
use App\Models\User;
use App\Services\Front\QrcodeService;
use App\Services\Wx\WxService;
use Illuminate\Http\Request;

class PayCallbackController extends Controller
{
    /**
     * 微信回调
     * @param Request $request
     * @return string
     */
    public function wxCallback(Request $request)
    {
        $xmldata = file_get_contents("php://input");
        /*libxml_disable_entity_loader(true);
        $xml_string = simplexml_load_string($xmldata,'SimpleXMLElement', LIBXML_NOCDATA);
        $result = json_decode(json_encode($xml_string),true);*/
        $result = xmlToArray($xmldata);
        $orderNo=$result['out_trade_no'];
        $wxPayApi = new WxPayApi();
        $sign = $wxPayApi->MakeSign($result);
        \Log::info("PayCallbackController wxCallback".$xmldata);

        if($sign === $result['sign']){//验证签名
            \Log::info("PayCallbackController wxCallback1".$result['sign']);
            try{
                \DB::beginTransaction();
                $order = Order::select("totalFee")->where('orderNo',$orderNo)->first();
                if(!$order){
                    throw new \Exception("订单不存在");
                }
                if($order['totalFee'] < 0){
                    throw new \Exception("订单金额错误".$order['totalFee']);
                }
                if($order['totalFee'] === $result['total_fee']){
//                    $status = Order::where(['orderNo'=>$orderNo, 'orderStatus'=>'NONPAYMENT'])->update(['orderStatus'=>'WAITDELIVER']);
                    $time = date("Y-m-d H:i:s");
                    $status = Order::where(['orderNo'=>$orderNo, 'orderStatus'=>'NONPAYMENT'])->update(['orderStatus'=>'ORDERFINISH','payTime'=>$time,'finishTime'=>$time]);
                    if(!$status){
                        throw new \Exception("修改订单状态失败");
                    }
                    $status = PaymentCallback::create(['callbackResult'=>$xmldata,'payType'=>"WX",'orderNo'=>$orderNo]);
                    if(!$status){
                        throw new \Exception("插入回调失败");
                    }
                    \DB::commit();
                    return "<xml>
                                <return_code><![CDATA[SUCCESS]]></return_code>
                                <return_msg><![CDATA[OK]]></return_msg>
                            </xml>";
                }else{
                    throw new \Exception("订单金额不一致");
                }
            }catch (\Exception $e){
                \DB::rollback();
                \Log::error("PayCallbackController wxCallback".$e->getMessage());
            }

        }else{
            \Log::error("PayCallbackController wxCallback 签名错误");
        }

    }

    /**
     * 支付宝回调
     * @param Request $request
     */
    public function aliCallback(Request $request)
    {
        $config = getAliConfig();
        $arr = $_POST;
        $alipaySevice = new AlipayTradeService($config);
        $result = $alipaySevice->check($arr);
        /* 实际验证过程建议商户添加以下校验。
           1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            4、验证app_id是否为该商户本身。
        */

        $orderNo = $arr['out_trade_no'];//商户订单号
        $totalAmount = $arr['total_amount'] * 100; //订单金额
        $appId = $arr['app_id'];
        $trade_status = $_POST['trade_status']; //交易状态
        if ($result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代
            try{
                \DB::beginTransaction();
                $order = Order::select("totalFee")->where('orderNo',$orderNo)->first();
                if(!$order){
                    throw new \Exception("订单不存在");
                }
                if($appId != env('ALI_APPID')){
                    throw new \Exception("appId错误");
                }
                $num = $totalAmount - $order['totalFee'];
                if($num !=  0 ){//
                    throw new \Exception("金额错误");
                }

                if ($trade_status == 'TRADE_FINISHED' || $trade_status== 'TRADE_SUCCESS') {

                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                    //如果有做过处理，不执行商户的业务程序

                    //注意：
                    //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    $status = Order::where(['orderNo'=>$orderNo, 'orderStatus'=>'NONPAYMENT'])->update(['orderStatus'=>'WAITDELIVER']);
                    if(!$status){
                        throw new \Exception("修改订单状态失败");
                    }
                    $status = PaymentCallback::create(['callbackResult'=>json_encode($arr),'payType'=>"ALI",'orderNo'=>$orderNo]);
                    if(!$status){
                        throw new \Exception("插入回调失败");
                    }
                    \DB::commit();
                }
                echo "success";        //请不要修改或删除
            }catch (\Exception $e){
                \DB::rollback();
                \Log::error("PayCallbackController aliCallback  ".$e->getMessage());
            }

        } else {
            //验证失败
            echo "fail";    //请不要修改或删除

        }
    }
}